from rest_framework import serializers
from .models import Task, Channel
from datetime import datetime
from django.utils.dateparse import parse_datetime
from rest_framework.response import Response

from .scheduler import scheduler


def send_dingtalk_job_by_id(task_id, content):
    print(f"任务内容:--- {content}: {datetime.now()}")
    result = Task.objects.filter(task_id=task_id).update(status="completed")
    print(f"更新 id 任务状态: %s" % result)


class TaskSerializer(serializers.ModelSerializer):
    # time = serializers.SerializerMethodField()
    time = serializers.DateTimeField()

    author = serializers.HiddenField(default=serializers.CurrentUserDefault())
    channel = serializers.SlugRelatedField(
        queryset=Channel.objects.all(),
        slug_field='channel_name',  # 告诉它匹配哪个字段
        allow_null=True,  # 如果允许为空要加上
        required=False
    )
    task_id = serializers.IntegerField(required=False, default=None)

    class Meta:
        model = Task
        fields = '__all__'
        read_only_fields = ('status',)

    def get_time(self, obj):
        print("get_time()被调用")
        if obj.time:
            return int(obj.time.timestamp() * 1000)
        return None

    def to_internal_value(self, validated_data):
        validated_data = validated_data.copy()
        # 如果 time 是整数（Unix时间戳），转换为 datetime 对象
        time_val = validated_data.get('time')
        if isinstance(time_val, int) or (isinstance(time_val, str) and time_val.isdigit()):
            # 你也可以判断是否是13位还是10位，这里假设前端传的是毫秒
            timestamp = int(time_val)
            if timestamp > 1e12:  # 毫秒
                timestamp = timestamp / 1000

            time_str = datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
            time_str_ins = parse_datetime(time_str)
            print(type(time_str))
            validated_data['time'] = time_str_ins
            print(validated_data)
        return super().to_internal_value(validated_data)

    def to_representation(self, instance):
        # 调用父类的 to_representation 方法
        representation = super().to_representation(instance)

        # 将 'time' 字段转换为 Unix 时间戳（秒级）
        if representation.get('time'):
            # 转换为 Unix 时间戳，返回秒级时间戳
            representation['time'] = int(instance.time.timestamp() * 1000)

        status_map = {
            'completed': '已完成',
            'in_progress': '进行中'
        }
        if 'status' in representation:
            representation['status'] = status_map.get(representation['status'], representation['status'])
        return representation

    def create(self, validated_data):
        # request = self.context.get('request')
        title = validated_data.get('title')
        run_time = validated_data.get('time')
        # run_time = parse_datetime(run_time_str)

        year = run_time.year
        month = run_time.month
        day = run_time.day
        hour = run_time.hour
        minute = run_time.minute

        if not title or not run_time:
            return Response({"error": "Invalid content or time"}, status=400)

        if not validated_data.get('task_id'):
            task_id = int(datetime.timestamp(datetime.now()))
        else:
            task_id = validated_data.get('task_id')
            task_delete_msg = Task.objects.filter(task_id=task_id).delete()
            # print("任务删除结果:%s" % task_delete_msg)

            select_result = scheduler.get_job(job_id=task_id)
            if select_result:
                job_delete_msg = scheduler.remove_job(job_id=task_id)
                print("任务删除结果:%s" % job_delete_msg)

        job_kwargs = {
            "func": send_dingtalk_job_by_id,
            "trigger": "cron",
            "id": str(task_id),
            "kwargs": {"content": title, "task_id": str(task_id)},
            "year": year,
            "month": month,
            "day": day,
            "hour": hour,
            "minute": minute,
            "replace_existing": "true"

        }

        task_result = scheduler.add_job(**job_kwargs)
        print(task_result)
        validated_data['task_id'] = str(task_id)
        return Task.objects.create(**validated_data)


class ChannelSerializer(serializers.ModelSerializer):
    author = serializers.HiddenField(default=serializers.CurrentUserDefault())
    channel_name = serializers.CharField()
    channel_type = serializers.ChoiceField(
        choices=['钉钉', '邮件']
    )
    channel_addr = serializers.CharField()

    class Meta:
        model = Channel
        fields = ['channel_name', 'author', 'channel_type', 'channel_addr', 'created_at']
        read_only_fields = ('create_date',)

    def to_representation(self, instance):
        # 调用父类的 to_representation 方法
        representation = super().to_representation(instance)

        status_map = {
            'DingDing': '钉钉',
            'Email': '邮件'
        }
        if 'channel_type' in representation:
            representation['channel_type'] = status_map.get(representation['channel_type'],
                                                            representation['channel_type'])
        return representation

    def to_internal_value(self, data):
        data = super().to_internal_value(data)
        if "channel_type" in data:
            mapping = {"钉钉": "DingDing", "邮件": "Email"}
            data["channel_type"] = mapping.get(data["channel_type"], data["channel_type"])
        return data

    def create(self, validated_data):
        """
        Create a new "article" instance
        """
        return Channel.objects.create(**validated_data)

    def update(self, instance, validated_data):
        """
        Use validated data to return an existing `Article`instance。"""
        instance.channel_name = validated_data.get('channel_name', instance.channel_name)
        instance.channel_type = validated_data.get('channel_type', instance.channel_type)
        instance.channel_addr = validated_data.get('channel_addr', instance.channel_addr)
        instance.save()
        return instance
